package cn.ac.iie.di.tools;

//import cn.ac.iie.tire.word.filter.ForumcomFilterMain;
import com.trs.ckm.soap.ABSHold;
import com.trs.ckm.soap.ABSResult;
import com.trs.ckm.soap.AbsTheme;
import com.trs.ckm.soap.CkmSoapException;
import com.trs.ckm.soap.PLOResult;
import com.trs.ckm.soap.RuleCATField;
import com.trs.ckm.soap.TrsCkmSoapClient;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.log4j.Logger;

public class TRSTools {

    //test
    private String trsclientip = "http://10.136.65.134:8000;http://10.136.65.135:8000;http://10.136.65.136:8000;http://10.136.65.137:8000;http://10.136.65.138:8000;http://10.136.65.139:8000;http://10.136.65.140:8000;http://10.136.65.141:8000;http://10.136.65.142:8000;http://10.136.65.143:8000;http://10.136.65.144:8000;http://10.136.65.145:8000;http://10.136.65.146:8000;http://10.136.65.147:8000;http://10.136.65.148:8000;http://10.136.65.149:8000;http://10.136.65.150:8000;http://10.136.65.51:8000";
//    private String trsclientip;
    private String trsUrls;
    private TrsCkmSoapClient client;
    private static final Logger LOG = Logger.getLogger(TRSTools.class.getName());

    public TRSTools(String trsclientip) {
        this.trsclientip = trsclientip;
        this.trsUrls = trsclientip;
    }

    private void init() {
//        LOG.info("TRS初始开始");
        this.client = new TrsCkmSoapClient();
        LOG.info("can use trsurl :" + this.trsUrls);
        this.client.SetServer(this.trsUrls, "admin", "trsadmin");
//        LOG.info("TRS初始结束");
    }

    /**
     * 得到可用的trsUrl 如果不可用就移除 如果集合中的url少于10那么就从新赋值配置信息
     *
     * @param urlString
     * @param urlD
     * @return
     */
    public String getTrsUrl(String urlString, String urlD) {
        List urlList = new ArrayList();
        String[] urlStrings = urlString.split(";");
        for (String url : urlStrings) {
            urlList.add(url);
        }
        if (urlList.size() < 10) {
            this.trsUrls = getTrsUrl(trsclientip, null);
            return this.trsUrls;
        }
        urlList.remove(urlD);
        LOG.info("remove the ip is " + urlD);
        String urlLists = urlList.toString().replaceAll(", ", ";");
        urlLists = urlLists.substring(1, urlLists.length() - 1);
        LOG.debug("now ,the trs client ip is " + urlLists);
        return urlLists;
    }
    
    public String[] getMKeyWordList(String cont) {
//        LOG.info("拓尔思");
        while (true) {
            if (this.client == null) {
                init();
//                LOG.info("拓尔思初始化");
            }
            try {
                ABSHold absHold = new ABSHold(5, 10);
//                LOG.info("拓尔思ABSText");
                LOG.debug("传入参数 "+ cont);
                ABSResult absResult = this.client.ABSText(cont, absHold);
                LOG.debug("传入参数1 "+ cont);
                
//                LOG.info("拓尔思getwordlist");
                String keywordStr = absResult.getwordlist();
                if ("".equals(keywordStr) || keywordStr == null) {
//                    LOG.info("拓尔思ABSTextaaa");
                    return new String[]{};
                } else {
//                     LOG.info("拓尔思ABSTextbbb");
                    return keywordStr.split(";");
                }
            } catch (CkmSoapException ex) {
                LOG.error("cont is : " + cont + " trserror  and continue" + ex);
                String errorStr = ex.toString();
                if (errorStr.contains("http")) {
                    String urlD = errorStr.substring(errorStr.indexOf("http"), errorStr.indexOf("8000") + 4);
                    this.trsUrls = getTrsUrl(this.trsUrls, urlD);
                    this.client = null;
                }
                
            } catch (Exception e) {
                if (this.client == null) {
                    init();
//                    LOG.info("拓尔思init");
                }
                LOG.error("cont is : " + cont + e, e);
            }
        }
    }

    public String getMabstract(String cont) {
        while (true) {
            if (this.client == null) {
                init();
            }
            try {
                ABSHold absHold = new ABSHold(5, 10);
//                AbsTheme[] GetAbsThemeList = this.client.GetAbsThemeList(cont, 0);
//                String tabs = GetAbsThemeList[0].getWord();
                ABSResult absResult = this.client.ABSText(cont, absHold);
                String tabs = absResult.getabs();
                if ("".equals(tabs) || tabs == null) {
                    return "";
                } else {
                    return tabs;
                }
            } catch (CkmSoapException ex) {
                LOG.error("cont is : " + cont + " trserror  and continue" + ex);
                String errorStr = ex.toString();
                if (errorStr.contains("http")) {
                    String urlD = errorStr.substring(errorStr.indexOf("http"), errorStr.indexOf("8000") + 4);
                    this.trsUrls = getTrsUrl(this.trsUrls, urlD);
                    this.client = null;
                }
            } catch (Exception e) {
                if (this.client == null) {
                    init();
                }
                LOG.error("cont is : " + cont + e, e);
            }
        }
    }

    public HashMap[] getMKeyWordVector(String cont) {
        while (true) {
            if (this.client == null) {
                init();
            }
            try {
                ABSHold absHold = new ABSHold(5, 10);
                ABSResult absResult = this.client.ABSText(cont, absHold);
                String keywordStr = absResult.getwordlist();
                if ("".equals(keywordStr) || keywordStr == null) {
                    HashMap[] vmmap = new HashMap[1];
                    HashMap vm = new HashMap();
                    vm.put("v", "");
                    vm.put("w", "");
                    vmmap[0] = vm;
//                    return new HashMap[]{};
                    return vmmap;
                } else {
                    String[] keywords = keywordStr.split(";");
                    HashMap[] keywordsmap = new HashMap[keywords.length];
                    for (int m = 0; m < keywords.length; m++) {
                        HashMap vm = new HashMap();
                        vm.put("v", keywords[m]);
                        vm.put("w", "");
                        keywordsmap[m] = vm;
                    }
                    return keywordsmap;
                }
            } catch (CkmSoapException ex) {
                LOG.error("cont is : " + cont + " trserror  and continue" + ex);
                String errorStr = ex.toString();
                if (errorStr.contains("http")) {
                    String urlD = errorStr.substring(errorStr.indexOf("http"), errorStr.indexOf("8000") + 4);
                    this.trsUrls = getTrsUrl(this.trsUrls, urlD);
                    this.client = null;
                }
            } catch (Exception e) {
                if (this.client == null) {
                    init();
                }
                LOG.error("cont is : " + cont + e, e);
            }
        }
    }

    public String getCountryProvnce(String cp,PLOResult result){
        //国家或者省份
        String tmp = null;
        RuleCATField[]  _objRuleCATField = new RuleCATField[1];
                        _objRuleCATField[0] = new RuleCATField(result.getword(),"正文");
                        try{
                            tmp =this.client.RuleCATClassifyText(cp, _objRuleCATField);
                            if(tmp != null && !tmp.trim().isEmpty())
                            {   
                                return tmp;
                            }else{
                                tmp = "";
                            }
                        }catch(Exception e){
                            e.printStackTrace();
                            return null;
                        }
                        return tmp;   
    }
    
    public HashMap<String, HashMap[]> getMXXVector(String cont) {
        while (true) {
            if (this.client == null) {
                init();
            }
            try {
                HashMap<String, HashMap[]> vectorMap = new HashMap<String, HashMap[]>();
                PLOResult[] result = this.client.PLOText(cont, 0x0001 | 0x1002);
                List<PLOResult> personList = new ArrayList<PLOResult>();
                List<PLOResult> organizationList = new ArrayList<PLOResult>();
                List<PLOResult> regionList = new ArrayList<PLOResult>();
                
                HashMap[] personmap = null;
                HashMap[] organizationmap = null;
                HashMap[] regionmap = null;
                List<HashMap> countrymap = new ArrayList<HashMap>();
                List<HashMap> provincemap = new ArrayList<HashMap>();
                
                if (result != null) {
                    for (int m = 0; m < result.length; m++) {
                        switch (result[m].gettype()) {
                            case 1001:
                                personList.add(result[m]);
                                break;
                            case 1003:
                                organizationList.add(result[m]);
                                break;
                            case 1002:
                                String country = getCountryProvnce("国家",result[m]);
                                String province = getCountryProvnce("省",result[m]);
                                //词频
                                int fq = result[m].getFQ();
                                HashMap vm = new HashMap();
                                vm.put("v",country);
                                vm.put("w",fq);
                                countrymap.add(vm);
                                HashMap vm2 = new HashMap();
                                vm2.put("v",province);
                                vm2.put("w",fq);
                                provincemap.add(vm2);
                                regionList.add(result[m]);
                                break;
                            default:
                                break;
                        }
                    }
                    
                    personmap = new HashMap[personList.size()];
                    for (int p = 0; p < personList.size(); p++) {
                        HashMap vm = new HashMap();
                        vm.put("v", personList.get(p).getword());
                        vm.put("w", personList.get(p).getFQ());
                        personmap[p] = vm;
                    }

                    organizationmap = new HashMap[organizationList.size()];
                    for (int o = 0; o < organizationList.size(); o++) {
                        HashMap vm = new HashMap();
                        vm.put("v", organizationList.get(o).getword());
                        vm.put("w", organizationList.get(o).getFQ());
                        organizationmap[o] = vm;
                    }

                    regionmap = new HashMap[regionList.size()];
                    for (int r = 0; r < regionList.size(); r++) {
                        HashMap vm = new HashMap();
                        vm.put("v", regionList.get(r).getword());
                        vm.put("w", regionList.get(r).getFQ());
                        regionmap[r] = vm;
                    }
                    
                 
                    
                } else {
                    HashMap[] vmmap2 = new HashMap[1];
                    HashMap vm2 = new HashMap();
                    vm2.put("v", "");
                    vm2.put("w", "");
                    vmmap2[0] = vm2;
                    personmap = vmmap2;
                    organizationmap = vmmap2;
                    regionmap = vmmap2;
                }
                vectorMap.put("person", personmap);
                vectorMap.put("organization", organizationmap);
                vectorMap.put("region", regionmap);
                vectorMap.put("countries", countrymap.toArray(new HashMap[countrymap.size()]));
                vectorMap.put("provinces", provincemap.toArray(new HashMap[provincemap.size()]));
                return vectorMap;
            } catch (CkmSoapException ex) {
                LOG.error("cont is : " + cont + " trserror  and continue" + ex);
                String errorStr = ex.toString();
                if (errorStr.contains("http")) {
                    String urlD = errorStr.substring(errorStr.indexOf("http"), errorStr.indexOf("8000") + 4);
                    this.trsUrls = getTrsUrl(this.trsUrls, urlD);
                    this.client = null;
                }
            } catch (Exception e) {
                if (this.client == null) {
                    init();
                }
                LOG.error("cont is : " + cont + e, e);
            }
        }
    }
    

    public HashMap<String, String[]> getMXX(String cont) {
        while (true) {
            if (this.client == null) {
                init();
            }
            try {
                HashMap<String, String[]> vectorMap = new HashMap<String, String[]>();
                PLOResult[] result = this.client.PLOText(cont, 0x0001);
                List<PLOResult> personList = new ArrayList<PLOResult>();
                List<PLOResult> organizationList = new ArrayList<PLOResult>();
                List<PLOResult> regionList = new ArrayList<PLOResult>();
                String[] person = new String[]{};
                String[] organization = new String[]{};
                String[] region = new String[]{};
                List<String> country =  new ArrayList<String>();
                List<String> province =  new ArrayList<String>();
                
                
                if (result != null) {
                    for (int m = 0; m < result.length; m++) {
                        switch (result[m].gettype()) {
                            case 1001:
                                personList.add(result[m]);
                                break;
                            case 1003:
                                organizationList.add(result[m]);
                                break;
                            case 1002:
                                String countryResult = getCountryProvnce("国家",result[m]);
                                String provinceResult = getCountryProvnce("省",result[m]);
                                country.add(countryResult);
                                province.add(provinceResult);
                                
                                regionList.add(result[m]);
                                break;
                            default:
                                break;
                        }
                    }
                    person = new String[personList.size()];
                    for (int p = 0; p < personList.size(); p++) {
                        person[p] = personList.get(p).getword();
                    }

                    organization = new String[organizationList.size()];
                    for (int o = 0; o < organizationList.size(); o++) {
                        organization[o] = organizationList.get(o).getword();
                    }

                    region = new String[regionList.size()];
                    for (int r = 0; r < regionList.size(); r++) {
                        region[r] = regionList.get(r).getword();
                    }
                }
                vectorMap.put("person", person);
                vectorMap.put("organization", organization);
                vectorMap.put("region", region);
                vectorMap.put("country", country.toArray(new String[country.size()]));
                vectorMap.put("province", province.toArray(new String[province.size()]));
                return vectorMap;
            } catch (CkmSoapException ex) {
                LOG.error("cont is : " + cont + " trserror  and continue" + ex);
                String errorStr = ex.toString();
                if (errorStr.contains("http")) {
                    String urlD = errorStr.substring(errorStr.indexOf("http"), errorStr.indexOf("8000") + 4);
                    this.trsUrls = getTrsUrl(this.trsUrls, urlD);
                    this.client = null;
                }
            } catch (Exception e) {
                if (this.client == null) {
                    init();
                }
                LOG.error("cont is : " + cont + e, e);
            }
        }
    }

    public long getMsentiment(String cont) {
        while (true) {
            if (this.client == null) {
                init();
            }
            try {
                long reNumber = -1;
                String resul = this.client.AppraiseParseLN("bb_pingjia_add_LN", cont);
                if (resul == null || "0".equals(resul) || "".equals(resul)) {
                    reNumber = -1;
                } else {
                    Float f = Float.valueOf(resul);
                    if (f > 0 && f <= 100) {
                        reNumber = 100;
                    } else if (f < 0 && f >= -100) {
                        reNumber = 0;
                    }
                }
                return reNumber;
            } catch (CkmSoapException ex) {
                LOG.error("cont is : " + cont + " trserror  and continue" + ex);
                String errorStr = ex.toString();
                if (errorStr.contains("http")) {
                    String urlD = errorStr.substring(errorStr.indexOf("http"), errorStr.indexOf("8000") + 4);
                    this.trsUrls = getTrsUrl(this.trsUrls, urlD);
                    this.client = null;
                }
            } catch (Exception e) {
                if (this.client == null) {
                    init();
                }
                LOG.error("cont is : " + cont + e, e);
            }
        }
    }

    public String[] getMCategory_Tag(String cont) {
        while (true) {
            if (this.client == null) {
                init();
            }
            try {
                RuleCATField[] fields = new RuleCATField[1];
                fields[0] = new RuleCATField(cont, "m_content");
                String rslt = this.client.RuleCATClassifyText("CNML_RULE", fields);
                if ("".equals(rslt) || rslt == null) {
                    return new String[]{};
                } else {
                    return rslt.split(";");
                }
            } catch (CkmSoapException ex) {
                LOG.error("cont is : " + cont + " trserror  and continue" + ex);
                String errorStr = ex.toString();
                if (errorStr.contains("http")) {
                    String urlD = errorStr.substring(errorStr.indexOf("http"), errorStr.indexOf("8000") + 4);
                    this.trsUrls = getTrsUrl(this.trsUrls, urlD);
                    this.client = null;
                }
            } catch (Exception e) {
                if (this.client == null) {
                    init();
                }
                LOG.error("cont is : " + cont + e, e);
            }
        }
    }

    public String[] getMCatagoryIndustry(String cont) {
        while (true) {
            if (this.client == null) {
                init();
            }
            RuleCATField[] fields = new RuleCATField[1];
            fields[0] = new RuleCATField(cont, "m_content");
            try {
                String rslt = this.client.RuleCATClassifyText("内容行业分类", fields);
                if ("".equals(rslt) || rslt == null) {
                    return new String[]{};
                } else {
                    return rslt.split(";");
                }
            } catch (CkmSoapException ex) {
                LOG.error("cont is : " + cont + " trserror  and continue" + ex);
                String errorStr = ex.toString();
                if (errorStr.contains("http")) {
                    String urlD = errorStr.substring(errorStr.indexOf("http"), errorStr.indexOf("8000") + 4);
                    this.trsUrls = getTrsUrl(this.trsUrls, urlD);
                    this.client = null;
                }
            } catch (Exception e) {
                if (this.client == null) {
                    init();
                }
                LOG.error("cont is : " + cont + e, e);
            }
        }
    }

    public String getMSiteCategory(String cont) {
        while (true) {
            if (this.client == null) {
                LOG.debug("client is null");
                init();
            }
            try {
                LOG.debug("start get ans");
                RuleCATField[] fields2 = new RuleCATField[1];
                fields2[0] = new RuleCATField(cont, "m_site_name");
                String rslt2 = this.client.RuleCATClassifyText("行业分类", fields2);
                if ("".equals(rslt2) || rslt2 == null) {
                    return "";
                } else {
                    return rslt2;
                }
            } catch (CkmSoapException ex) {
                LOG.error("cont is : " + cont + " trserror  and continue" + ex);
                String errorStr = ex.toString();
                if (errorStr.contains("http")) {
                    String urlD = errorStr.substring(errorStr.indexOf("http"), errorStr.indexOf("8000") + 4);
                    this.trsUrls = getTrsUrl(this.trsUrls, urlD);
                    this.client = null;
                }
            } catch (Exception e) {
                if (this.client == null) {
                    init();
                }
                LOG.error("cont is : " + cont + e, e);
            }
        }
    }

    public static void main(String[] args) {
        TrsCkmSoapClient client = new TrsCkmSoapClient();
        TRSTools trs = new TRSTools("http://localhost:9999");
        client.SetServer("http://localhost:9999;http://localhost:9510", "admin", "trsadmin");
//        trsTools.getMKeyWordList("护法运动是指1917年7月到1918年5月，以孙中山为首的资产阶级革命党人为维护临时约法、恢复国会，联合西南军阀共同进行了反对北洋军阀独裁统治的斗争。\n"
//                + "又称护法战争。所谓“护法”指的是护卫《中华民国临时约法》，打倒北洋军阀专政的虚假共和，重新建立新生共和的民主法统。");

//          trsTools.getMKeyWordList("少时诵诗书所");
          
          
//        String abs = trs.getMabstract("国家食品药品监督管理总局药品医疗器械");
//        System.out.println(abs);
//
//        HashMap[] keywordsmap = trs.getMKeyWordVector("国家食品药品监督管理总局药品医疗器械");
//        System.out.println(keywordsmap);

        HashMap mxxVector = trs.getMXXVector("中华人民共和国 吉林省 新闻");
//        for (Iterator columnsit = mxxVector.entrySet().iterator(); columnsit.hasNext();) {
//            Map.Entry<String, HashMap[]> entry = (Map.Entry<String, HashMap[]>) columnsit.next();
//            if ("person".equals(entry.getKey())) {
//                System.out.println(entry.getValue());
//            } else if ("organization".equals(entry.getKey())) {
//                System.out.println(entry.getValue());
//            } else if ("region".equals(entry.getKey())) {
//                System.out.println(entry.getValue());
//            }
//        }
//
//        long msentiment = trs.getMsentiment("国家食品药品监督管理总局药品医疗器械");
//        System.out.println(msentiment);
//
//        String[] mCategory_Tag = trs.getMCategory_Tag("国家食品药品监督管理总局药品医疗器械");
//        System.out.println(mCategory_Tag);

//        String[] mCatagoryIndustry = trs.getMCatagoryIndustry("国家食品药品监督管理总局药品医疗器械");
//        System.out.println(mCatagoryIndustry);
//        long mSiteCategory = trs.getMSiteCategory("国家食品药品监督管理总局药品医疗器械");
//        System.out.println(mSiteCategory);
//        String rslt = "";
//        if (rslt == null || "".equals(rslt)) {
//            System.out.println("null");
//        } else {
//            System.out.println("not null");
//        }
    }
}
